"""
@author: zjc
@file: userinfo.py
@time: 2023/3/5 19:53
"""
from flask_restful import Resource,Api
from flask import Blueprint,request
from libs.response import response_data
from model.userdb.userinfo import User
from forms.user import UserForm,LoginForm
from libs.auth import login,create_token
from werkzeug.security import generate_password_hash
from model import db

user_bp=Blueprint("user_bp",__name__,url_prefix="/v1")
api=Api(user_bp)

class UserView(Resource):
    def post(self):
        # try:
            data=request.json
            form=UserForm(data=data)
            username=data.get("username")
            if form.validate():
                User.create_user(username,
                               password=form.password.data
                               )
                return response_data(message="注册成功")
            else:
                return response_data(code=1,message=form.errors)
        # except:
        #         return response_data(code=1,message="注册失败")


    @login
    def get(self):
        id=request.args.get("id")
        if  id == "":
            user_all = User.query.all()
            user_list = []
            for i in user_all:
                tmp_dict = dict(i)
                user_list.append(tmp_dict)
            return response_data(data=user_list)
        else:
            user = User.query.get(int(id))
            if user:
                tmp_dict=dict(user)
                return response_data(data=tmp_dict)
            else:
                return response_data(code=1, message="查询失败，没有该用户!")

class LoginView(Resource):
    # @login
    def post(self):
        try:
            data=request.json
            form=LoginForm(data=data)
            user=form.validate()
            if user:
                # 验证通过，生成token
                token = create_token(user.id)
                return response_data(message="login success",
                                         data={"token": token,
                                               "username":user.username})
            else:
                return response_data(message=form.errors)
        except:
                return response_data(code=1,message="登录失败")
    # @login
    def put(self):
        try:
            data=request.json
            username=data.get("username")
            user=User.query.filter(User.username==username).first()
            if user:
                password=data.get("password")
                user.password=generate_password_hash(password)
                db.session.commit()
                return response_data(message="重置密码成功")
            else:
                return response_data(message="用户名错误,重置密码失败")
        except:
            return response_data(code=1, message="重置密码失败")


api.add_resource(UserView,"/user")
api.add_resource(LoginView,"/login")